<?php
define('Acan_Afun',1);
//获取aurl	url路由
$Aurl = Afun_urls();
$Aurl_num = count($Aurl);
for ($i=3; $i < $Aurl_num; $i=$i+2) {
	$_GET[$Aurl[$i]] = $Aurl[$i+1];
}
function Afun_session($data=''){
	if(!empty($data)){$_SESSION[Acan_app_name] = $data;}
	return $_SESSION[Acan_app_name];
}
function Afun_uid($id=''){
	if(!empty($id)){$_SESSION[Acan_app_name]['uid']=$id;}
	return $_SESSION[Acan_app_name]['uid'];
}
function Afun_error($content=''){
	Afun_header(404);
	Afun_log('访问页面不存在|错误内容:'.$content);
	echo '<title>404</title>您访问的页面错误!<br>'.$content;
	exit;
}
function Ajson_encode($data){
	return Afun_json_encode($data);
	/*if(PHP_VERSION=='5.3.6'){
		return preg_replace("#\\\u([0-9a-f]{4})#ie", "iconv('UCS-2','UTF-8',pack('H4','\\1'))",json_encode($data));
	}else{
		return Afun_json_encode($data);
	}*/
}
function Afun_json($data,$type=false){
	//输出JSON字符串
	ob_end_clean();ob_start();
	header('Content-type: application/json; charset=UTF-8');
	if($type && function_exists('json_encode')){
		echo json_encode($data);
	}else{
		echo Ajson_encode($data);
	}
	exit;
}
function Afun_jsonp($data,$type=false){
	//输出JSON字符串
	ob_end_clean();ob_start();
	header('Content-type: application/json; charset=UTF-8');
	echo 'jsonpcall(';
	if($type && function_exists('json_encode')){
		echo json_encode($data);
	}else{
		echo Ajson_encode($data);
	}
	echo ');';
	exit;
}
function Afun_post_auth(){
	if(empty($_POST)){Afun_refresh('非法访问','referrer');exit;}
}
function Afun_url(){/*aurl 路由*/
	if(!empty($_GET['aurl'])){
		return explode("/",preg_replace("/\.(html|htm|shtml)/",'',$_GET['aurl']));
	}else{
		return Afun_urls();
	}
}
function Afun_urls(){/*aurl 路由*/
	if(!empty($_GET['i'])){
		return explode("/",preg_replace("/\.(html|htm|shtml)/",'',$_GET['a']));
	}else{
		return array('index');
	}
}
function Afun_url_other(){
	foreach($_GET as $key=>$val){
		if(in_array($key,array('a','apage','aorder')) || empty($key)){continue;}
			$url .= '/'.$key.'/'.$val;
	}
	return $url;
}

//获取其它GET参数
function Afun_otherurl($norr=''){
	foreach ($_GET as $k => $v) {
		if(in_array($k,array('app','mod','act','id','i'))) continue;
		if(is_array($norr) && in_array($k,$norr)) continue;
		if(is_string($norr) && $k==$norr) continue;
		$otherurl .= "&$k=$v";
	}
	return $otherurl;
}
//日志
function Afun_log($data,$type='sys'){
	Afun_acan_new('log')->log_write($data,$type);
	return true;
}
//返回header 状态
function Afun_header($status = '200'){
	if($status == '404'){
		$data['status'] = 'HTTP/1.0 404 Not Found';
	}
	header($data['status']);
}
	

//--数据库连接
function Afun_db($type='mysql',$data=''){
	if($type=='mysql' || $type=='pgsql'){
		if(!is_array($data))
		$data = array(
			'host'=>Acan_db_host,
			'user'=>Acan_db_user,
			'pass'=>Acan_db_pass,
			'name'=>Acan_db_name,
			'port'=>Acan_db_port,
			'charset'=>Acan_db_charset
		);
	}elseif($type=='sqlite'){
		$data = array('path'=>Acan_sqlite_path,'charset'=>Acan_db_charset);
	}
	return Afun_acan_new($type,$data);
}
function Afun_db_uc(){
	define('UC_CONNECT','mysql');				// 连接 UCenter 的方式: mysql/NULL, 默认为空时为 fscoketopen()
	// mysql 是直接连接的数据库, 为了效率, 建议采用 mysql
	//数据库相关 (mysql 连接时, 并且没有设置 UC_DBLINK 时, 需要配置以下变量)
	define('UC_DBHOST','db.abans.cn');			// UCenter 数据库主机
	define('UC_DBUSER','root');				// UCenter 数据库用户名
	define('UC_DBPW','');					// UCenter 数据库密码
	define('UC_DBNAME','abans_uc');				// UCenter 数据库名称
	define('UC_DBCHARSET','utf8');				// UCenter 数据库字符集
	define('UC_DBTABLEPRE','abans_uc.uc_');			// UCenter 数据库表前缀
	$data = array(
		'host'=>UC_DBHOST,
		'user'=>UC_DBUSER,
		'pass'=>UC_DBPW,
		'name'=>UC_DBNAME,
		'charset'=>UC_DBCHARSET,
	);
	return Afun_acan_new('sql',$data);
}

//--数据库连接
function Afun_db_link($data,$type='mysql'){
	if($type=='pgsql')
		return Afun_pdo($type,$data['host'],$data['user'],$data['pass'],$data['name'],$data['port'],$data['charset']);
	elseif(!empty($data['host']))
		return Afun_pdo($type,$data['host'],$data['user'],$data['pass'],$data['name'],$data['port'],$data['charset']);
	else
		return Afun_sqlite_pdo($data['path'],$data['charset']);
}

//mysql PDO连接
function Afun_pdo($type,$host,$user,$pass,$name,$port='3306',$charset='utf8'){
	global $Adb;
	if(!is_object($Adb) || !empty($host)){
		try {
			$Adb=new PDO($type.":host=".$host.";port=".$port.";dbname=".$name,$user,$pass);
			$Adb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		//	$adb=new PDO("mysql:host=".$host.";dbname=".$name,$user,$pass,array(PDO::ATTR_PERSISTENT =>true,PDO::ATTR_TIMEOUT => 10));
			if($type=='mysql') $Adb->query('set names '.$charset.';');
			return $Adb;
		} catch (PDOException $e) {
			$rs->msg = 'mysql连接信息: '.str_replace(array("\r","\n"),'',Afun_charset($e->getMessage())).'<br>mysql连接失败: 请修改mysql配置(/acan/acan/config/aconfig.php)';
			$rs->status = $e->getCode();
			Afun_json($rs);
		}
	}else{
		return $Adb;
	}
}
//sqlite PDO连接
function Afun_sqlite_pdo($path,$charset='utf8'){
	try {
		$adb=new PDO("sqlite:".$path,"","",array(PDO::ATTR_PERSISTENT =>true,PDO::ATTR_TIMEOUT => 30));
		$adb->query('set names '.$charset.';');
		return $adb;
	} catch (PDOException $e) {
		echo 'sqlite连接失败: 请修改sqlite配置(/acan/acan/config/aconfig.php)<br>';
		echo 'sqlite连接信息: ' . $e->getMessage();
	}
}
//mysql 连接
function Afun_mysql_link($host,$user,$pass,$name,$charset='utf8'){
	$conn=mysql_connect($host,$user,$pass) or die('数据连接错误');
	mysql_query("SET NAMES '$charset'",$conn);
	mysql_select_db($name) or die('不能链接到指定数据库 ('.$name.') because of : '.mysql_error());
	return $conn;
}

//生成html实静态文件
function Afun_html_cache($content){
	global $_GET,$aurl;
	$ahtml = Afun_cache_get('abans_html_cache');
	if(empty($ahtml)){
		$ahtml = '';
	//	Afun_cache_set('abans_html_cache',$ahtml,600);//写入缓存
	}
	$filename = '/'.isset($_GET['aurl']) ? $_GET['a']:$_GET['aurl'];
	$path = A_ROOT.'temp/ahtml'.$filename;
	//--首页
	if($_SERVER["REQUEST_URI"]=='/index.php'){
		if(!file_exists(A_ROOT.'temp/ahtml/')){
			Afunc_file()->amkdirm(A_ROOT.'temp/ahtml/');
		}
		file_put_contents(A_ROOT.'temp/ahtml/index.html',$content);
		return true;
	}
	//--缓存的页面
	if($_SERVER["SCRIPT_NAME"]=='/index.php' && $if_html_cache=='1'){
		$count_aurl = count(Afun_url($_GET['aurl']));
		$pathinfo = pathinfo($path);
		Afunc_file()->amkdirm($pathinfo['dirname']);
		file_put_contents($path,$content);
		if($count_aurl == '1'){
			$pathb = explode(".html",$path);
			$pathb =$pathb[0].'/index.html';
			$pathinfo = pathinfo($pathb);
			Afunc_file()->amkdirm($pathinfo['dirname']);
			file_put_contents($pathb,$content);
		}
	}
}


function Afun_request($val){/*获取请求值(GET 或者 POST) (GET优先)*/
	if($_GET[$val]){
		return $_GET[$val];
	}elseif($_POST[$val]){
		return $_POST[$val];
	}else{
		return "";
	}
}

//====new 类
function Afun_new($name,$info=''){/*初始化自定义类*/
	//分解目录
	$arr = explode('/',$name);
	$arrnum = count($arr);
	$newname = 'Com_'.$arr[$arrnum-1];
	if(count($arr) == 1){
		$arrpath = Acan_app_name;
	}else{
		for ($i=0; $i < $arrnum-1; $i++) { 
			if(empty($arrpath))
				$arrpath = $arr[$i];
			else
				$arrpath .= '/'.$arr[$i];
		}
	}
	$class_path = A_ROOT.'com/public/'.$newname.'.php';
	if(!file_exists($class_path)){
		$class_path = A_ROOT.'com/'.$arrpath.'/'.$newname.'.php';
	}
	if(!file_exists($class_path)){
		exit('未定义的类'.$class_path.'<br>'.$newname.'.php');
	}
	include_once($class_path);
	$Aclass = new $newname($info);
	return $Aclass;
}

function Afun_acan_new($name,$info=''){/*初始化框架类*/
	$arr = explode('/',$name);
	$newname = 'Aclass_'.$arr[count($arr)-1];
	$class_path = AcanROOT.'class/Aclass_'.$name.'.php';
	if(!file_exists($class_path)){
		exit('未定义的类'.$name);
	}
	include_once($class_path);
	$Aclass = new $newname($info);
	return $Aclass;
}
//====new 类 end


//获取当前地址
function Afun_get_url(){
	return 'http://'.$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
}
//获取操作系统
function Afun_get_os(){
	if(PATH_SEPARATOR==':') return 'Linux';
	else return 'Windows';
}


//转换编码
function Afun_charset($val,$charset="utf8",$type="text/html"){/*转换编码*/
	if(@in_array($charset,array("utf8","utf-8","UTF8","UTF-8"))||$charset==""){
	//	@header("Content-Type: ".$type."; charset=utf-8");
		$val = iconv('GB2312','utf-8',$val);
	}elseif(@in_array($charset,array("gbk","gb2312","GB2312","GB-2312"))){
	//	@header("Content-Type: ".$type."; charset=gb2312");
		$val = iconv('utf-8','GB2312',$val);
	}
	return $val;
}
function Afun_charsets($val,$charset="utf8"){/*转换编码*/
	if(is_array($val)){
		foreach ($val as $k => $v) {
			$obj[$k] = Afun_charsets($v,$charset="utf8");
		}
	}elseif(is_object($val) ){
		foreach ($val as $k => $v) {
			$obj->$k = Afun_charsets($v,$charset="utf8");
		}
	}elseif(is_string($val)){
		return Afun_charset($val,$charset="utf8");
	}else{
		return $val;
	}
	return $obj;
}


function Afun_delall($str){
	foreach($str as $value){
		if(empty($allid))
			$allid = "'".(int)$value."'";
		else
			$allid.= ",'".(int)$value."'";
	}
	return $allid;
}
//--数组合并为字符串，供sql条件
function Afun_arr_unisql($arr,$type='str'){
	if($type=='str'){
		$fh = "'";
	}elseif($type=='int'){
		$fh = "";
	}
	foreach($arr as $v){
		if(empty($allid))
			$allid = $fh.$v.$fh;
		else
			$allid.= ",".$fh.$v.$fh;
	}
	return $allid;
}

//获取IP
function Afun_get_ip(){
	if($_SERVER["HTTP_X_REAL_IP"]){
		return $_SERVER['HTTP_X_REAL_IP'];
	}else{
		return $_SERVER['REMOTE_ADDR'];
	}
}
//获取时间
function Afun_get_time($type='datatime'){
	if($type == 'date'){
		$adatatime = date("Y-m-d",$_SERVER['REQUEST_TIME']);
	}elseif($type == 'time'){
		$adatatime = $_SERVER['REQUEST_TIME'];
	}elseif($type == 'datatime'){
		$adatatime = date("Y-m-d H:i:s",$_SERVER['REQUEST_TIME']);
	}else{
		$adatatime = date($type,$_SERVER['REQUEST_TIME']);
	}
	return $adatatime;
}
//时间戳转date
function Afun_time_date($time,$type="Y-m-d H:i:s"){
	if($time > 0){
		return date($type,$time);
	}else{
		return date($type,$_SERVER['REQUEST_TIME']);
	}
}
//时间加减法
function Afun_time_ex($time,$add=1,$type="d"){
	if(!is_numeric($time)){
		$time = strtotime($time);
	}
	//月份加减
	if($type=='m'){
		if($add>0){
			$daynum = date('t',$time);
		}else{
			$oldY = date('Y',$time);
			$oldm = date('n',$time);
			$oldp = $oldm+$add;
			if($oldp<1){
				$oldY += floor($oldp/12);
				$oldm = fmod($oldp, 12);
				if($oldm==0){$oldm = 12;$oldY--;}
			}elseif($oldp>0){
				$oldm = $oldp;
			}
			$daynum = date('t',strtotime($oldY.'-'.$oldm));
		}
		$newtime = $time+(86400*$daynum*$add);
		return $newtime;
		$oldY = date('Y',$time);
		$oldm = date('n',$time);
		$oldp = $oldm+$add;
		if($oldp>12){
			$oldY += floor($oldp/12);
			$oldm = fmod($oldp, 12);
			if($oldm==0){$oldm = 12;$oldY--;}
		}elseif($oldp<=12){
			$oldm = $oldp;
		}
		$oldo = date('d H:i:s',$time);
		$odate = $oldY.'-'.$oldm.'-'.$oldo;
	}elseif($type=='d'){
		$newtime = $time+(86400*$add);
		return $newtime;
		$oldY = date('Y',$time);
		$oldd = date('z',$time);
		$oldp = $oldd+$add;
		if(fmod($oldY, 4)==0){$Ynum = 366;}else{$Ynum = 365;}
		if($oldp>$Ynum){
			$oldY += floor($oldp/$Ynum);
			$oldd = fmod($oldp, $Ynum);
			if($oldd==0){$oldm = $Ynum;$oldY--;}
		}elseif($oldp<=$Ynum){
			$oldd = $oldp;
		}
	}
	return strtotime($odate);
}


/*截字方法*/
function Afun_substr_utf8($string,$length,$start=0,$add='......'){
	$chars = $string;
	$i=0;
	do{
		if (preg_match ("/[0-9a-zA-Z]/", $chars[$i])){//纯英文
			$m++;
		}else{$n++;}//非英文字节,
		$k = $n/3+$m/2;
		$l = $n/3+$m;//最终截取长度；$l = $n/3+$m*2？
		$i++;
	}while($k < $length);
	$str1 = mb_substr($string,$start,$l,'utf-8').$add;//保证不会出现乱码
	return $str1;
}

//指定长度分割字符串
function Afun_substr_arr($str,$length){
	$i=0;
	while(1){
		$strr[$i] = mb_substr($str,$i*$length,$length,'utf-8');
		if(empty($strr[$i])){
			break;
		}
		$i++;
	}
	return $strr;
}

//-------------------------------Afun_ahtmls------------------------
function Afun_ahtmls($value,$op="0"){
	if($op=="s"){
		$value=preg_replace("/<pre>(.*)<\/pre>/seU","Afun_ahtmlshow('\\1')",$value);
	}else if($op=="r"){
		$value=preg_replace("/<pre>(.*)<\/pre>/seU","Afun_ahtmlread('\\1')",$value);
	}else if($op=="w"){
		$value=preg_replace("/<pre>(.*)<\/pre>/seU","Afun_ahtmlwrite('\\1')",$value);
	}else if($op=="r2"){
		$value=preg_replace("/<pre>(.*)<\/pre>/seU","Afun_ahtmlread2('\\1')",$value);
	}
	return $value;
}
function Afun_ahtmlshow($str){
	$str = str_replace(array('&amp;lt;','&amp;gt;','\"',"\'"), array('&lt;','&gt;','"',"'"), $str);
	$str='<pre>'.$str.'</pre>';
	return $str;
}
function Afun_ahtmlread($str){
	$str = str_replace(array('<','>','\"',"\'"), array('&lt;','&gt;','"',"'"), $str);
	$str = preg_replace("/(\r\n|\n|\r)/i","<br />",$str);
	$str='<pre>'.$str.'</pre>';
	return $str;
}
function Afun_html_code($str){
	$str = str_replace(array('<','>','\"',"\'"), array('&lt;','&gt;','"',"'"), $str);
	//$str = preg_replace("/(\r\n|\n|\r)/i","<br />",$str);
	return $str;
}
function Afun_ahtmlread2($str){
	$str = str_replace(array('<','>','\"',"\'"), array('&lt;','&gt;','"',"'"), $str);
	$str = str_replace(array('&lt;','&gt;','\n'), array('&amp;lt;','&amp;gt;','<br />'), $str);
	$str='<pre>'.$str.'</pre>';
	return $str;
}
function Afun_ahtmlwrite($str){
	$str = preg_replace("/(<br \/>)/i","",$str);
	$str = str_replace(array('<','>','\"',"\'"), array('&lt;','&gt;','"',"'"), $str);
	$str = str_replace(array('&lt;','&gt;','\n'), array('&amp;lt;','&amp;gt;','<br />'), $str);
	$str='<pre>'.$str.'</pre>';
	return $str;
}
//-------------------------------Afun_ahtmls end------------------------

/*防SQL注入*/
function Afun_sql_save($sql) {
	//$pattern = "/select|insert|update|delete|drop|alter|truncate|union|\%|\'|\"|\\\|char\(/i";
	$pattern = "/drop|alter|truncate|union|DUMPFILE|CONCAT\(|SLEEP\(|IFNULL\(|CAST\(|LENGTH\(|MID\(|IF\(|ORD\(|0x|\"|char\(/i";
	preg_match($pattern, $sql, $matches);
	if(count($matches)>0){
		print_r($matches);
		echo $sql;
		echo 'Afun.php ！警告！您的IP已经被系统记录、请不要输入非法地址！';
		exit;
	}else{
		return $sql;
	}
}



/*加密方式*/
function Afun_sha256($str){
	return hash('sha256',$str.Acan_auth_key);
}
function Afun_pass($str){
	return hash('sha1',$str.Acan_auth_key);
}
function Afun_auth_hash($uid,$times){
	return hash('sha1',$uid.$times.Acan_auth_key);
}
function Afun_md5($str){
	$adoll .='m@i';
	$adoll .=$str;
	$adoll .='lys';
	return $str = mhash(MHASH_MD5,$str);
}

/*formats sizes	统计大小*/
function Afun_format_size ($x,$un=1) {
	$a = array('bytes', 'kb', 'mb', 'gb');
	$i = 0;
	while ($x >= 1024) {$i++;$x = $x / 1024;}
	if($un=='1'){$ext = ' '.$a[$i];}else{$ext = '';}
	return number_format($x, ($i > 0)?2:0, '.', ',').$ext;
}


/*
//数组排序
	$data = array(
		array("id" => 1, "name" => "abc", "rating" => 3),
		array("id" => 2, "name" => "bac", "rating" => 1),
		array("id" => 3, "name" => "bca", "rating" => 4),
		array("id" => 4, "name" => "cab", "rating" => 3),
	);
	foreach ($data as $key => $value) {
		$name[$key] = $value['name'];
		$rating[$key] = $value['rating'];
	}

	print_r(Afun_arr_sort($data));
*/


/*数组排序*/
function Afun_arr_sort($data,$order='id',$by='DESC'){
	if(empty($data[0][$order])){
		return $data;
	}
	if($by=='DESC'){
		$bys = SORT_DESC;
	}else{
		$bys = SORT_ASC;
	}
	foreach ($data as $i => $value) {
		$doll[$order][$i] = $value[$order];
	}
	array_multisort($doll[$order],$bys, $data,SORT_DESC);
	return $data;
}
//批量删除数组元素
function Afun_arr_remove($arr,$remove){
	if(count($arr)==0){return $arr;}
	foreach($arr as $k=>$v){
		if(in_array($k,$remove)){
			unset($arr[$k]);
		}
	}
	return $arr;
}
//批量取数组元素
function Afun_arr_get($arr,$get){
	if(count($arr)==0){return array();}
	foreach($get as $k=>$v){
		if($arr[$v]){
			$arrs[$v] = $arr[$v];
		}
	}
	return $arrs;
}
function Afun_arr_obj($arr){
	if(!is_array($arr)){return $arr;}
	foreach ($arr as $key => $val) {
		if(is_int($key) && $type != 'key'){
			$type == 'ini';
			$obj[] = Afun_arr_obj($val);
		}else if(!is_int($key)){
			if($type == 'ini'){
				unset($obj);
			}
			$type = 'key';
			$obj->$key = Afun_arr_obj($val);
		}
	}
	return $obj;
}
//对象转数组
function Afun_obj_arr($obj){
	if(!is_object($obj)){return $obj;}
	foreach($obj as $k=>$v){
		if(is_object($v)){$v = Afun_obj_arr($v);}
		if(!is_string($k)){
			$k = (string)$k;
		}
		$arr[$k] = $v;
	}
	return $arr;
}

/*返回用于替换的字符串*/
function Afun_replace_val($str){
	$arra = array("\\", "/", ".", "<", ">", "[", "]", "$", "+", "-", "?", "!");
	$arrb = array("\\\\", "\\/", "\\.", "\\<", "\\>", "\\[", "\\]", "\\$", "\\+", "\\-", "\\?", "\\!");
	return str_replace($arra, $arrb, $str);
}

/*返回用于替换的字符串*/
function Afun_mysql_is_null($str){
	if($str === null){
		return "null";
	}
	return "'".Afun_replace_mysql($str)."'";
}
//--mysql 导出的替换
function Afun_replace_mysql($str){
	$arra = array("'", "\r", "\n");
	$arrb = array("''", '\r', '\n');
	return str_replace($arra, $arrb, $str);
}

function Afun_urlencode($str){
	return str_replace("%2F","$2F",urlencode($str));
}
function Afun_urldecode($str){
	return urldecode(str_replace("$2F","%2F",$str));
}

function Afun_parseurl($url=""){
	$url = rawurlencode(mb_convert_encoding($url, 'utf-8', 'gb2312'));
	$a = array("%3A", "%2F", "%40", "%20");
	$b = array(":", "/", "@", " ");
	$url = str_replace($a, $b, $url);
	return $url;
}

//--获取url中的where条件
function Afun_url_where_get(){
	$awhere = $_GET['awhere'];
	if(empty($awhere)){
		return 0;
	}
	$awhere = explode(',',$awhere);
	foreach($awhere as $key=>$val){
		$arr = explode('=',$val);
		$where['where'][$arr[0]] = $arr[1];
	}
	$where['num'] = count($awhere);
	return $where;
}
//--将url中的where条件的数据合并成sql条件
function Afun_url_where_sql($wheres){
	if($wheres['num']>0){
		foreach($wheres['where'] as $key=>$val){
			$where .= ' and `'.$key.'`=\''.$val.'\'';
		}
		return $where;
	}else{
		return "";
	}
}

/* file */
//创建文件夹
function Afun_file_mkdir($str){
	$str = Afun_file_charset($str);
	if(file_exists($str))
		$msg="文件夹已经存在!";
	else if(Afun_file_mkdirm($str))
		$msg="创建文件夹成功!";
	return $msg;
}
//递归创建文件夹
function Afun_file_mkdirm($path){
	if(!file_exists($path)){
		Afun_file_mkdirm(dirname($path));
		mkdir($path, 0777);
	}
	return true;
}
//递归删除文件夹
function Afun_file_rmdirm($dir){
	if($objs = glob($dir."/*")){
		foreach($objs as $obj) {
			is_dir($obj)? Afun_file_rmdirm($obj) : unlink($obj);
		}
	}
	rmdir($dir);
	return true;
}
//文件名编码
function Afun_file_charset($str){
	Afun_charset($str,Acan_os_charset);
	return true;
}
//email
function Afun_mail($tomail,$toname,$title,$body,$attachment=null,$frommail=null,$fromname=null){
	$op = Afunc_option();
	define('Acan_email_user',$op->get('Acan_email_user'));				//用户名
	define('Acan_email_pass',$op->get('Acan_email_pass'));				//密码
	define('Acan_email_smtp',$op->get('Acan_email_smtp'));				//smtp 地址
	define('Acan_email_port',$op->get('Acan_email_port'));				//smtp 端口
	define('Acan_email_frommail',$op->get('Acan_email_frommail'));		//来源email地址
	define('Acan_email_fromname',$op->get('Acan_email_fromname'));		//来源名称
	define('Acan_email_replymail',$op->get('Acan_email_replymail'));	//回复email地址
	define('Acan_email_replyname',$op->get('Acan_email_replyname'));	//回复名称
	define('Acan_email_pop',$op->get('Acan_email_pop'));				//pop 地址
	define('Acan_email_pport',$op->get('Acan_email_pport'));			//pop 端口
	$data = array(
		'title'=>$title,
		'body'=>$body,
		'tomail'=>$tomail,
		'toname'=>$toname,
		'frommail'=>$frommail,
		'fromname'=>$fromname,
		'replymail'=>$replymail,
		'replyname'=>$replyname,
		'attachment'=>$attachment
		);
	return Afun_mail_one($data);
}
function Afun_mail_one($data){
	$title = $data['title'];
	$body = $data['body'];
	$tomail = $data['tomail'];
	$toname = $data['toname'];
	$frommail = $data['frommail'];
	$fromname = $data['fromname'];
	$replymail = $data['replymail'];
	$replyname = $data['replyname'];
	$attachment = $data['attachment'];
	
	if(empty($frommail)){
		if(defined('Acan_email_frommail'))
			$frommail = Acan_email_frommail;
		else
			$msg = '未设置发送邮箱';
	}
	if(empty($fromname) && defined('Acan_email_fromname')){
		$fromname = Acan_email_fromname;
	}
	if(empty($replymail)){
		if(defined('Acan_email_replymail'))
			$replymail = Acan_email_replymail;
		else
			$replymail = $frommail;
	}
	if(empty($replyname)){
		if(defined('Acan_email_replyname'))
			$replyname = Acan_email_replyname;
		else
			$replyname = $frommail;
	}
	if($msg){
		echo $msg;
		return false;
	}
	require_once(AcanROOT.'class/lib/phpmailer/class.phpmailer.php');
	$mail = new PHPMailer(true);
	$mail->IsSMTP();
	try {
		$mail->CharSet ="UTF-8";
		$mail->Host       = Acan_email_smtp;	// SMTP server
		$mail->SMTPDebug  = 1;					// enables SMTP debug information (for testing)
		$mail->SMTPAuth   = true;				// enable SMTP authentication
		$mail->Host       = Acan_email_smtp;	// sets the SMTP server
		$mail->Port       = Acan_email_port;	// set the SMTP port for the GMAIL server
		$mail->Username   = Acan_email_user;	// SMTP account username
		$mail->Password   = Acan_email_pass;	// SMTP account password
		$mail->AddReplyTo($replymail, $replyname);
		if(is_array($tomail)){
			foreach($tomail as $k=>$v){
				$mail->AddAddress($k,$v);
			}
		}else{
			$mail->AddAddress($tomail,$toname);
		}
		$mail->SetFrom($frommail, $fromname);
		$mail->AddReplyTo($replymail, $replyname);
		$mail->Subject = $title;
	//	$mail->AltBody = $body;
		$mail->MsgHTML($body);	//获取模板文件
		if(is_array($attachment)){
			foreach($attachment as $k=>$v){
				$mail->AddAttachment($v['path'],$v['name']);
			}
		}elseif(!empty($attachment)){
			$mail->AddAttachment($attachment);
		}
	//	$mail->AddAttachment($attachment);					// 附件
	//	$mail->AddAttachment('images/phpmailer_mini.gif');	// 附件
		$mail->Send();
		return true;
		//echo "Message Sent OK\n";
	} catch (phpmailerException $e) {
		echo $e->errorMessage(); //Pretty error messages from PHPMailer
	} catch (Exception $e) {
		echo $e->getMessage(); //Boring error messages from anything else!
	}
	return false;
}

//CMD 初始化
function Afun_cmd_init(){
	define('Acan_cmd_path_linux','/anmp/s/php/bin/php');			//CMD 执行路径 linux
	define('Acan_cmd_path_win','E:/s/php/php.exe -c E:\s\config\php.ini');			//CMD 执行路径 windows
	define('Acan_cmd_charset','gbk');			//CMD 输出编码
}
//获取 cmd 路径
function Afun_get_cmd_path(){
	Afun_cmd_init();
	if(Afun_get_os() == 'Linux'){
		return Acan_cmd_path_linux;
	}else if(Afun_get_os() == 'Windows'){
		return Acan_cmd_path_win;
	}
}
//--CMD模式显示中文文字
function Afun_cmd_echo($val){
	Afun_cmd_init();
	echo Afun_charset($val."\n",Acan_cmd_charset);
}
function Afun_run_cmd($cmd){
	return Afun_charset(`$cmd`);
}
//执行shell命令
function Afun_run_shell($sh){
	return `$sh`;
}
//分页
function Afun_apage($obj=''){
	return Afun_acan_new("page",$obj)->apage();
}
//用户
function Afunc_user(){
	return Afun_new("user");
}
//--用户组
function Afunc_group($appid=''){
	return Afun_new('group',$appid);
}
//导航
function Afunc_nav(){
	return Afun_acan_new("nav");
}
//模型
function Afunc_file(){
	return Afun_acan_new("file");
}
//模型
function Afunc_model(){
	return Afun_acan_new("model");
}
//枚举
function Afunc_enum(){
	return Afun_acan_new("enum");
}
//模型
function Afunc_auth(){
	return Afun_acan_new("auth");
}
function Afunc_html(){
	return Afun_acan_new('html');
}
//--选项
function Afunc_option($key=''){
	return Afun_acan_new('option',$key);
}
//--扩展信息更新
function Afunc_info($dbname=''){
	return Afun_acan_new("info",$dbname);
}
//--日志类
function Afunc_log(){
	return Afun_acan_new('log');
}
//--地区类
function Afunc_area(){
	return Afun_acan_new('area');
}
function Afun_Atemplate($path){
	if(strpos($path, '/') === false){
		$path = Acan_tpl_public.$path;
	}else{
		$path = Acan_tpl_path.Acan_apptpl_path.$path;
	}
	return "<? include template('".$path."'); ?>";
}

//--广告
function Afun_ad($name){
	$model = Afun_cache_get('ad/name_'.$name);
	if(empty($model)){
		$model = Afun_db()->model(Acan_table_ad)->ofind("name='$name'");
		if($model->time_end > time()){
			$cache_time = $model->time_end - time();
		}else if($model->time_end==0){
			$cache_time = 0;
		}
		Afun_cache_set('ad/name_'.$name,$model,$cache_time);//写入缓存
	}
	if($model->time_start > time() || ($model->time_end > 0 && $model->time_end < time())){return;}
	if(empty($model->code)){return;}//无代码直接返回
	$arr->src = '/index.php?a=index/other/'.$model->id;
	$arr->style = $model->style;
	$arr->class = 'acan_iframe_other';
	$arr->frameborder = "0";
	$arr->scrolling = "no";
	$arr->allowtransparency = "true";
	$arr->hspace = "0";
	$arr->vspace = "0";
	$arr->marginheight = "0";
	$arr->marginwidth = "0";
	return Afunc_html()->tag('iframe',$arr);
}

//Afun_defined_constants();
function Afun_defined_constants(){
	$constants = get_defined_constants(true);
	foreach($constants['user'] as $key=>$val){
		$krr = explode('_',$key);
		$n = count($krr);
	}
}
function Afun_defined_functions(){
	$functions=get_defined_functions();
	foreach($functions as $key=>$val){}
}
	
//--css
function Afun_css_height_content($content){
	$size = 20;
	if(empty($content)){return 0;}
	$num = count(explode("\r\n",$content));
	if($num>1){$height = $num*$size;}
	if(empty($height)){
		$num = count(explode("\n",$content));
		if($num>0){$height = $num*$size;}
	}
	if(empty($height)){
		$num = count(explode("\r",$content));
		if($num>0){$height = $num*$size;}
	}
	if(empty($height)){
		$num = count(explode("<br>",$content));
		if($num>0){$height = $num*$size;}
	}
	if($height>=600){$height = 600;}
	return $height;
}

// 替换常量(数组,KEY,前缀)
function Afun_replace_define($content,$arr,$brr,$key,$qz=''){
	foreach($arr as $b=>$valb){
		$stra[] = '/\''.$qz.$key.'_'.$b.'\',\''.Afun_replace_val($brr[$b]).'\'/i';//原值
		$strb[] = '\''.$qz.$key.'_'.$b.'\',\''.$arr[$b].'\'';//新值
	}
	return preg_replace($stra,$strb,$content);
}
// 替换数组(数组,KEY,前缀)
function Afun_replace_array($content,$arr,$brr,$key){
	foreach($arr as $b=>$valb){
		$stra[] = '/\$'.$key.'\[\''.$b.'\'\]\=\''.Afun_replace_val($brr[$b]).'\'/i';
		$strb[] = "\$".$key."['".$b."']='".$valb."'";
	}
	return preg_replace($stra,$strb,$content);
}

//--允许访问的域名
function Afun_allowdomain($host=''){
	if(empty($host)){
		$host = $_SERVER['HTTP_HOST'];
	}
	$allow = array(
		'www.abans.cn',
		'local.abans.cn',
		'localhost:82',
	);
	if(!in_array($host, $allow)){
		Afun_header(404);
		Afun_log('访问域名错误|错误域名:'.$host);
		echo '<title>404</title>您访问的页面错误!点击进入<a href="www.abans.cn">www.abans.cn</a>';
		exit;
	}
}
/*统计程序内存使用*/
function Afun_memory_usage() {
	$memory	 = ( ! function_exists('memory_get_usage')) ? '0' : round(memory_get_usage()/1024/1024, 2).'MB';
	return $memory;
}

function Afun_debug(){
	if(Acan_debug == '1'){
		echo $_SESSION['acan']['bug'];
	}
}
function Afun_debug_ready(){
	$_SESSION['acan']['debug'] = '';
	unset($_SESSION['mysql']['sql']);
}
function Afun_debug_mysql($sql,$time){
	if(Acan_debug == '1'){
		$_SESSION['mysql'][] = array('sql'=>$sql,'time'=>$time);
	}
}
function Afun_runtime_html(){
	$endtime=gettime();echo '执行'.round($endtime- Acan_run_startime,3).'秒,使用'.Afun_memory_usage().'内存,'.mysql_query_times().'次数据查询';
}

function __call($v, $s) {
	// Note: value of $name is case sensitive.
	echo "不存在的方法为：'$v' "
	. implode(', ', $s). "\n";
}

//set_error_handler('error_handler');
//	$error = Afun_error_show(error_get_last());
//	print_r($error);
//debug_backtrace();
//debug_print_backtrace();
/*
函数名						描述											PHP
debug_backtrace()			生成 backtrace。								4
debug_print_backtrace()		输出 backtrace。								5
error_get_last()			获得最后发生的错误。							5
error_log()					向服务器错误记录、文件或远程目标发送一个错误。	4
error_reporting()			规定报告哪个错误。								4
restore_error_handler()		恢复之前的错误处理程序。						4
restore_exception_handler()	恢复之前的异常处理程序。						5
set_error_handler()			设置用户自定义的错误处理函数。					4
set_exception_handler()		设置用户自定义的异常处理函数。					5
trigger_error()				创建用户自定义的错误消息。						4
user_error()				trigger_error() 的别名。						4
*/


function error_handler($type, $message, $file, $line, $argv){
	$error['type'] = $type;
	$error['message'] = $message;
	$error['file'] = $file;
	$error['line'] = $line;
	$error['argv'] = $argv;
	Afun_error_show($error);
}

function Afun_error_show($error){
	
	$error_cn = array(
		'1'=>'致命的运行时错误',
		'2'=>'非致命的错误',
		'4'=>'编译时语法解析错误',
		'8'=>'运行时提示',
		'16'=>'由 PHP 内部生成的错误',
		'32'=>'由 PHP 内部生成的警告',
		'64'=>'由 Zend 脚本引擎内部生成的错误',
		'128'=>'由 Zend 脚本引擎内部生成的警告',
		'256'=>'由于调用 trigger_error() 函数生成的运行时错误',
		'512'=>'由于调用 trigger_error() 函数生成的运行时警告',
		'1024'=>'由于调用 trigger_error() 函数生成的运行时提示',
		'1024'=>'运行时提示',
		'4096'=>'可捕获的致命错误。（参阅 set_error_handler()）',
		'8191'=>'所有的错误和警告，除了 E_STRICT',
	);
	$error_en = array(
		
		'1'=>'E_ERROR',
		'2'=>'E_WARNING',
		'4'=>'E_PARSE',
		'8'=>'E_NOTICE',
		'16'=>'E_CORE_ERROR',
		'32'=>'E_CORE_WARNING',
		'64'=>'E_COMPILE_ERROR',
		'128'=>'E_COMPILE_WARNING',
		'256'=>'E_USER_ERROR',
		'512'=>'E_USER_WARNING',
		'1024'=>'E_USER_NOTICE',
		'2048'=>'E_STRICT',
		'4096'=>'E_RECOVERABLE_ERROR',
		'8191'=>'E_ALL'
	);
	
	
	$html = '';
	
	if($error['type']){
		$html .= '<hr>错误等级: '.$error_en[$error['type']].' '.$error_cn[$error['type']];
	}
	if($error['message']){
		$html .= '<br>错误信息: '.$error['message'];
	}
	if($error['file']){
		$html .= '<br>错误文件: '.$error['file'];
		if($error['line']){
			$html .= ' 第'.$error['line'].'行.';
		}
	}
	if($error['argv']){
	//	$html .= '<br> '.print_r($error['argv']);
	}
	$_SESSION['acan']['bug'] = $html;
	//echo $html;
}

//计算mysql查询次数
function mysql_query_times($i=0){
	static $a=0;
	$a = $a+$i;
	return $a;
}
//累计mysql查询sql
function mysql_query_sql($sql=''){
	static $a=array();
	if(!empty($sql)) $a[] = $sql;
	return $a;
}

//身份证前17位算最后一位
function Afun_id_card_18($str){
	//传17位的数字可得到最后一位校验码;
	$wi=array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);//17位数对应的加权因子，自左至右;
	$yi=array(0,1,2,3,4,5,6,7,8,9,10);//余数;
	$vi=array("1","0","X","9","8","7","6","5","4","3","2");//余数对应的校验码;
	$sum=0;$y;
	if(strlen($str)==17){
		for($i=0;$i<count($wi);$i++){
			$sum+=substr($str,$i,1)* $wi[$i];//这种方式更简洁;
		}
		return $vi[$sum%11];
	}else{
		return false;
	}
}
//身份证效验
function Afun_id_card_check($str){
	if(Afun_id_card_18(substr($str,0,17))==substr($str,17,1)){
		return true;
	}else{
		return false;
	}
}

function Afun_curl($type='get',$url,$data='',$gzip='1',$arr=array()){
	if($type=='get'){
		$url .= Afun_urlstr($data);
	}
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	if($arr['header']) curl_setopt($curl, CURLOPT_HTTPHEADER, $arr['header']);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
	if($gzip=='1'){
		curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
	}
	if($type=='post'){
		$post_data = Afun_urlstr($data);
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
	}
	$file_contents = curl_redir_exec($curl);
	curl_close($curl);
	list($obj['header'], $obj['data']) = explode("\r\n\r\n", $file_contents, 2);
	return $obj;
}
function Afun_urlstr ($data,$parent=''){
	$str='';$add='';
	if(is_object($data) || is_array($data)){
		foreach ($data as $k=>$v){
			$add=$k;
			if($parent || (strlen($parent)==1 && $parent==0)){$add = $parent."[".$k."]";}
			if(is_object($data) || is_array($data)){
				$str .= Afun_urlstr($v,$add);
			}else{
				$str .= "&".$add."=".$v;
			}
		};
	}else{if($parent || (strlen($parent)==1 && $parent==0)){$str = "&".$parent."=".$data;}else{$str = "&".$data;}}
	return $str;
}
function curl_redir_exec($ch,$debug=""){
	static $curl_loops = 0;
	static $curl_max_loops = 20;
	if ($curl_loops++ >= $curl_max_loops){
		$curl_loops = 0;
		return FALSE;
	}
	curl_setopt($ch, CURLOPT_HEADER, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$data = curl_exec($ch);
	
	$debbbb = $data;
	list($header, $data) = explode("\n\n", $data, 2);
	$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	if ($http_code == 301 || $http_code == 302){
		$matches = array();
		preg_match('/Location:(.*?)\n/', $header, $matches);
		$url = @parse_url(trim(array_pop($matches)));
		if (!$url){
			$curl_loops = 0;
			return $data;
		}
		$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
		$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
		curl_setopt($ch, CURLOPT_URL, $new_url);
		return curl_redir_exec($ch);
	} else {
		$curl_loops=0;
		return $debbbb;
	}
}
?>